#ifndef WEATHERTOOL_H
#define WEATHERTOOL_H
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <map>
#include <QFile>
#include <QCoreApplication>

class WeatherTool{
public:
    WeatherTool(){
        QString fileName = QCoreApplication::applicationDirPath();
        fileName+="/citycode-2019-08-23.json";
        QFile file(fileName);
        file.open(QIODevice::ReadOnly|QIODevice::Text);
        QByteArray json = file.readAll();
        file.close();
        QJsonParseError err;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(json,&err);
        QJsonArray citys = jsonDoc.array();
        for(int i =0 ;i<citys.size();i++){
            QString code = citys.at(i).toObject().value("city_code").toString();
            QString city = citys.at(i).toObject().value("city_name").toString();
            if(code.size()>0)
                m_mapCity2Code.insert(std::pair<QString,QString>(city,code));
        }
        fileName = QCoreApplication::applicationDirPath();
        fileName +="/type2spell.json";
        QFile file1(fileName);
        file1.open(QIODevice::ReadOnly|QIODevice::Text);
        QByteArray json1 = file1.readAll();
        file1.close();
        QJsonParseError err1;
        QJsonDocument jsonDoc1 = QJsonDocument::fromJson(json1,&err);
        QJsonArray types = jsonDoc1.array();
        for(int i = 0;i< types.at(0).toArray().size();i++){
            QString ch = types.at(0).toArray().at(i).toString();
            QString sp = types.at(1).toArray().at(i).toString();
            m_mapType.insert(std::pair<QString,QString>(ch,sp));
        }
    }
    QString operator[](const QString& city){
        std::map<QString,QString>::iterator it = m_mapCity2Code.find(city);
        if(it==m_mapCity2Code.end()){
            it = m_mapCity2Code.find(city+"市");
        }
        if(it==m_mapCity2Code.end()){
            it = m_mapCity2Code.find(city+"县");
        }
        if(it==m_mapCity2Code.end()){
            it = m_mapCity2Code.find(city+"区");
        }
        if(it!=m_mapCity2Code.end()){
            return it->second;
        }
        return "000000000";
    }
    QString Chinese2Spell(QString chType){
        std::map<QString,QString>::iterator it = m_mapType.find(chType);
        if(it!=m_mapType.end()){
            return it->second;
        }
        return NULL;
    }
private:
   std::map<QString,QString> m_mapCity2Code;//城市转邮编
   std::map<QString,QString> m_mapType;//中文转拼音
};

#endif // WEATHERTOOL_H
